package com.cy.pj.brand.controller;

import com.cy.pj.brand.pojo.Brand;
import com.cy.pj.brand.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class BrandController {
    @Autowired
    private BrandService brandService;

    @GetMapping("/brand/doFindById/{id}")
    public String doFindById(@PathVariable Integer id,Model model){
        Brand brand=brandService.findById(id);
        model.addAttribute("brand",brand);
        return "/brand/brand-update";
    }

    @PostMapping("/brand/doUpdateBrand")
    public String doUpdateBrand(Brand brand,Model model){
        System.out.println("update.brand="+brand);
        brandService.updateBrand(brand);
        List<Brand> list= brandService.findBrands(null);
        model.addAttribute("list",list);
        return "brand/brand";
    }


    @PostMapping("/brand/doSaveBrand")
    public String doSaveBrand(Brand brand,Model model){
        System.out.println("save.brand="+brand);
        brandService.saveBrand(brand);
        List<Brand> list= brandService.findBrands(null);
        model.addAttribute("list",list);
        return "brand/brand";
    }

    @GetMapping("/brand/doAddUI")
    public String doAddUI(){
        return "brand/brand-add";
    }

    @GetMapping("/brand/doDeleteById/{id}")
    public String doDeleteById(@PathVariable Integer id,Model model){
       // System.out.println(id);
        brandService.deleteById(id);
        List<Brand> list= brandService.findBrands(null);
        model.addAttribute("list",list);
        return "brand/brand";
    }

    //rest风格(一种软件架构编码风格)的url定义 ，可以更好的实现跨平台
    //其语法为：a/b/{c}/d/{e},在url可以定义变量，这个变量需要使用{}括起来
    //@PathVariable 注解用于修饰方法参数，目的是告诉spring mvc，参数的值来自于url
    @RequestMapping(value = {"/brand/doFindBrands","/brand/doFindBrands/{name}"})
    public String doFindBrands(@PathVariable(required = false) String name, Model model){
       List<Brand> list= brandService.findBrands(name);
       model.addAttribute("list",list);
       return "brand/brand";//第一个brand为目录，第二个brand为view name

    }
}
